'use client'

import { zodResolver } from '@hookform/resolvers/zod';
import React, { useState } from 'react'
import { useForm } from 'react-hook-form';
import * as z from "zod";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { signIn } from '@/lib/auth-client';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';

const loginSchema = z.object({
    email: z.string().email('Invalid email address'),
    password: z.string().min(6, 'Password must be at least 6 characters'),
})

type LoginFormvalues = z.infer<typeof loginSchema>

const LoginFormInfo: { name: keyof LoginFormvalues, label: string, type?: string }[] = [{
    name: 'email',
    label: 'Email',
}, {
    name: 'password',
    label: 'Password',
    type: 'password',
}]

export default function LoginForm() {
    const router = useRouter()

    const [isLoading, setIsLoading] = useState(false)

    const form = useForm<LoginFormvalues>({
        resolver: zodResolver(loginSchema),
        defaultValues: {
            email: "",
            password: "",
        },
    })

    const onSubmit = async (values: LoginFormvalues) => {
        setIsLoading(true)
        try {
            const { error } = await signIn.email({
                email: values.email,
                password: values.password,
                rememberMe: true,
            })
            if (error) {
                toast('Failed to login')
                return
            }
            router.push('/')
            toast('Successfully login')

        } catch (error) {
            console.log(error)
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                {LoginFormInfo.map((item) => {
                    return (
                        <FormField
                            key={item.name}
                            control={form.control}
                            name={item.name}
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{item.label}</FormLabel>
                                    <FormControl>
                                        <Input type={item.type || 'text'} {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    )
                })}

                <Button type="submit" className='w-full cursor-pointer' disabled={isLoading}>{isLoading ? '...' : 'Submit'}</Button>
            </form>
        </Form>
    )
}